package impl

import (
	"context"
	"gark-elastic-job/common"
	"github.com/olivere/elastic/v7"
	logger "github.com/sirupsen/logrus"
	"time"
)

// elasticsearch 可以提前设置index的mapping,提升后面日志的查询性能
type EsSaver struct {
	client           *elastic.Client
	executionLogChan chan common.JobExecutionLog
	index            string
}

func NewEsSaver(c *elastic.Client, index string) *EsSaver {
	es := &EsSaver{
		client:           c,
		executionLogChan: make(chan common.JobExecutionLog),
		index:            index,
	}
	go es.loop()
	return es
}

func (e *EsSaver) Save(executionLog common.JobExecutionLog) {
	e.executionLogChan <- executionLog
}

func (e *EsSaver) Update(executionLog common.JobExecutionLog) {
	e.executionLogChan <- executionLog
}

func (e *EsSaver) CheckExist(id string) (bool, error) {
	result, err := e.client.Exists().Index(e.index).Id(id).Do(context.Background())
	if err != nil {
		return false, err
	}
	return result, nil
}

func (e *EsSaver) loop() {
	for {
		for eventLog, ok := <-e.executionLogChan; ok; {
			indexService := e.client.Index().Index(e.index).BodyJson(eventLog)
			if eventLog.ID != "" {
				indexService.Id(eventLog.ID)
			}
			_, err := indexService.Do(context.Background())
			if err != nil {
				logger.Errorf("failed to save execution log: %v to es, err: %v", eventLog, err)
				continue
			}
		}
		time.Sleep(500 * time.Millisecond)
	}
}
